package com.hd.trans.utils;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;


/**
 * 
 * @ClassName: StringUtils 
 * @Description: 字符串工具类
 * @author yangHuang
 * @date 2016-3-18 上午1:05:54 
 *
 */
public class StringUtils {

	private StringUtils(){
	}

	/** 判断字符串是否为空 */
	public static boolean isEmpty(String paramString) {

		if (paramString == null || paramString.isEmpty())//|| "null".equals(paramString)
			return true;

		for (int i = 0; i < paramString.length(); i++) {
			char c = paramString.charAt(i);
			if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
				return false;
			}
		}
		return true;
	}

	private static final Pattern URL_PATTERN = Pattern
			.compile("^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]");

	/** 判断是否为网页 */
	public static boolean isURL(String url) {
		if (url == null || url.trim().length() == 0)
			return false;
		return StringUtils.URL_PATTERN.matcher(url).matches();
	}

	/** 字符串转Long */
	public static long toLong(String obj) {
		try {
			return Long.parseLong(obj);
		} catch (Exception e) {
		}
		return 0;
	}

	/** 字符串转整数 */
	public static int toInt(String str, int defValue) {
		try {
			return Integer.parseInt(str);
		} catch (Exception e) {
		}
		return defValue;
	}
	
	public static int toInt(String str){
		return toInt(str, 0);
	}


	@SuppressLint("SimpleDateFormat")
	private final static ThreadLocal<SimpleDateFormat> dateDay = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd");
		}
	};


	@SuppressLint("SimpleDateFormat")
	private final static ThreadLocal<SimpleDateFormat> dateMouth = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("MM-dd HH:mm");
		}
	};

	/**
	 * 将时间戳转为(MM-DD HH:MM)格式的字符串
	 * 
	 * @param timeStr
	 *            时间戳
	 * @return
	 */
	public static String getDate(String timeStr) {
		long t = toLong(timeStr);

		if (isEmpty(timeStr) || t == 0)
			return "null";

		StringBuffer sb = new StringBuffer();

		sb.append(dateMouth.get().format(t * 1000));

		return sb.toString();
	}

	/**
	 * 得到一个格式化的时间
	 *
	 * @param time
	 *            时间 秒
	 * @return 时：分：秒
	 */
	public static String getFormatTime(long time) {
		long second = time % 60;
		long minute = (time % 3600) / 60;
		long hour = time / 3600;
		return String.format("%02d:%02d:%02d", hour,minute,second);
	}

	public static String getFormatMillisTime(long time) {
		return getFormatTime(time / 1000L);
	}
	

    /**
     *  判断字符是否为中文(算法2)
     */
    public static boolean isChineseChar(char c) { 
    	Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
    	
		if ( ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
			|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
			|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
			|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
			|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
			|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
		) {
			return true;
		}
		return false;
    }

	/**
	 * 将字符串按固定长度切割成字符子串
	 * @param text 需要切割的字符串
	 * @param pageSize 字符子串的长度
	 * @return
	 */
	public static String[] splitStringByLength(String text, int pageSize) {
		if (isEmpty(text))
			return null;
		int pageNum = text.length() % pageSize > 0 ? 1 + text.length() / pageSize : text.length() / pageSize;
		String[] split = new String[pageNum];
		for (int i = 0; i < pageNum; i++) {

			if (i < (pageNum - 1)) {
				split[i] = text.substring(i * pageSize, (i + 1) * pageSize);
			} else {
				split[i] = text.substring(i * pageSize);
			}

		}
		return split;
	}

	public static String template(String orgin, String translation) {
		return "原文:\r\n" + orgin + "\r\n" + "译文:\r\n" + translation;
	}


	/**
	 * 字符串分割（句子分割）
	 */
	public static List<String> splitSentence(String string) {
		List<String> sentenceList = new ArrayList<>();
		//检查字符串有无
		if(TextUtils.isEmpty(string)){
			return sentenceList;
		}
		//检查字符串长度
		if(string.length()<=100){
			sentenceList.add(string);
			return sentenceList;
		}
		String[] sentences = string.split("[.,，。?？!！\n]");//"\\.|,|，|。|\\?|？|!|！|\n"
		StringBuilder stringBuilder = new StringBuilder();
		int index = 0;
		for(int i = 0;i<sentences.length;i++){
			String sentence = sentences[i];
			if(sentence == null)continue;
			stringBuilder.append(sentence);
			index += sentence.length();
			if(index > string.length()-1){
				index = string.length()-1;
			}
			stringBuilder.append(string.charAt(index));
			index += 1;
			if(stringBuilder.toString().trim().length() >= 50){
				sentenceList.add(carve(stringBuilder.toString()));
				stringBuilder.replace(0, stringBuilder.length(), "");
			}else {
				if(i == sentences.length-1){
					if(stringBuilder.toString().trim().length() > 25){
						sentenceList.add(carve(stringBuilder.toString()));
					}else {
						if(i>0){
							String s = sentenceList.remove(sentenceList.size()-1);
							sentenceList.add(carve(s + stringBuilder.toString()));
						}else {
							sentenceList.add(carve(stringBuilder.toString()));
						}
					}
				}
			}
		}
		return sentenceList;
	}

	private static String carve(String string){
		if(string == null) return null;
		return string.trim().replace("\n", "");
	}
}
